/**
 * Created by limei on 2018/6/12.
 */
import MYCONF from '../../myconf'
import env from "../../util/env";
import MapHelper from "../../util/map-helper";

export default class cityMapLayerHandler {
  constructor(_view) {
    this._view = _view;
    this.map = _view.map;
  }

  //城市一张图
  addCityMapLayer(){
    const map = this._view.map;
    let sourceData = {
      "type": "FeatureCollection",
      "features": []
    };
    this._view.cityMapData.map((item) => {
      let itemObj = {
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [item.lon,item.lat]
        },
        "properties": {
          ...item,
          "iconId":`icon-${item.typeid}`
        }
      }
      sourceData.features.push(itemObj);
    });
    if (!map.getSource('city-icon')) {
      map.addSource('city-icon', {
        type: 'geojson',
        data: sourceData,
      })
    }
    if (!map.getLayer('city-icon')) {
      map.addLayer({
        "id": "city-icon",
        "source": "city-icon",
        "type": "symbol",
        layout: {
          'icon-image': "{iconId}",
          'icon-size': 0.8,
          "text-offset": [0, 0.6],
          "text-anchor": "top",
          "icon-allow-overlap": false,  //图标允许压盖
          "text-allow-overlap": true,   //图标覆盖文字允许压盖
        },
      })
    }
  }

  //过滤城市一张图类别
  filterCityMapLayer(){
    const map = this._view.map;
    let id = this._view.in_type.typeid;
    if(this._view.in_type.typeid === 0){
      if(map.getLayer('city-icon')) map.setFilter('city-icon',['!=', 'typeid', '']);
    }else{
      if(map.getLayer('city-icon')){
        map.setFilter('city-icon',['==', 'typeid', id]);
      }
    }
  }

  getRange(pointList,itemPoint){
    const map = this._view.map;
    if(pointList.length>1){
      this.filterPoint(map,pointList);
    }
    if(pointList.length == 1){
      this.locateToCityMap(itemPoint);
    }
  }

  locateToCityMap(info){
    const map = this._view.map;
    let coordinate = [info.lon,info.lat];
    let id = info.id;
    if(map.getLayer('city-icon')) map.setFilter('city-icon',['==', 'id', id]);
    map.flyTo({
      center:coordinate,
      zoom:15,
      speed:1.5
    })
   // console.log("info是"+info.id)
   let cityPopup = new minemap.Popup({closeOnClick: true, offset: [22, -30]})
      .setLngLat(coordinate)
      .setDOMContent(MapHelper.addCityMapPopup(info))
      .addTo(map);
    env.popups.push(cityPopup);
  }

  filterPoint(map,pointList){
    let wholePath = turf.lineString(pointList);
    let bbox = turf.bbox(wholePath);
    map.stop();
    map.fitBounds([[bbox[0], bbox[1]], [bbox[2], bbox[3]]], {
      linear: true,
      padding: {
        top: 300,
        bottom: 300,
        left: 600,
        right: 600
      }
    });
  }


}
